﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace ESAM_Assignment_3
{
    public partial class ChangePassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string fullname = "";
            string name = Request.QueryString["username"];
            if (name == null)
            {
                Response.Redirect("Error.aspx");
            }
            else
            {
                fullname = UserClass.GetFullname(name);
            }
            if ((bool)Session[Common.ESAM_LOGIN] == false)
            {
                Response.Redirect("Default.aspx");
            }
            if ((string)Session[Common.ESAM_FULLNAME] != fullname)
            {
				Response.Redirect("Default.aspx?Username=" + Session["username"]);
            }
            //Retrieve the user's details from the cookie
            CookieClass myCookie = new CookieClass();
            myCookie.ReadCookie(Context);
			string hashpass = FormsAuthentication.HashPasswordForStoringInConfigFile(myCookie.Password, "sha1");

			lblUsername.Text = myCookie.Username;
        }

        protected void btnChangePassword_Click(object sender, EventArgs e)
        {
            string username = Request.QueryString["Username"];
            string CurrentPassword = tbxCurrentPassword.Text;
            string NewPassword = tbxNewPassword.Text;

			if (tbxNewPassword.Text == tbxRetypePassword.Text)
			{
				string hashcurpass = FormsAuthentication.HashPasswordForStoringInConfigFile(CurrentPassword, "sha1");
				string hashnewpass = FormsAuthentication.HashPasswordForStoringInConfigFile(NewPassword, "sha1");

				bool status = UserClass.ChangePassword(username, hashcurpass, hashnewpass);

				if (status)
				{
					lblStatus.Text = "Success. You new password has been saved. Please use the new password at your next logon.";
					lblStatus.ForeColor = System.Drawing.Color.Blue;

					//Store user's details since password has been changed
					CookieClass myCookie = new CookieClass();
					myCookie.WriteCookie(Context, username, NewPassword);
				}
				else
				{
					lblStatus.Text = "Error! Your new password cannot be saved. Incorrect current password? Please try again.";
					lblStatus.ForeColor = System.Drawing.Color.Red;
				}
			}
			else
			{
				lblStatus.Text = "Error! Your new password do not match! Please try again.";
				lblStatus.ForeColor = System.Drawing.Color.Red;
			}
            //Reset the textboxes
            tbxCurrentPassword.Text = "";
            tbxNewPassword.Text = "";
            tbxRetypePassword.Text = "";
        }
    }
}